import { NextApiRequest, NextApiResponse } from 'next';
import { withIronSessionApiRoute } from 'iron-session/next';
import { ironOptions } from '@/config';
import { ISession } from '@/pages/api';
import { prepareConnection } from '@/db';
import { Tag } from '@/db/entity';

const get = async (req: NextApiRequest, res: NextApiResponse) => {
  const session: ISession = req.session;
  const db = await prepareConnection();
  const tagRepo = db.getRepository(Tag);

  const followTags = await tagRepo.find({
    relations: ['users'],
    where: (callback: any) => {
      // 寻找 user_id 等于 session.userId 的数据
      callback.where('user_id = :id', {
        id: Number(session.userId)
      })
    }
  })

  const allTags = await tagRepo.find({
    relations: ['users'],
  })

  res.status(200).json({
    code: 200,
    msg: 'success',
    data: {
      followTags,
      allTags
    }
  })
}

export default withIronSessionApiRoute(get, ironOptions)